<!DOCTYPE html>
<html lang="en">
<head>
    <title>go2rtc - File Editor</title>
    <meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://unpkg.com/ace-builds@1.33.1/src-min/ace.js"></script>
    <style>
        body {
            font-family: Arial, Helvetica, sans-serif;
            background-color: white;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
        }

        html, body, #config {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
<script src="main.js"></script>
<div>
    <button id="save">Save & Restart</button>
</div>
<br>
<div id="config"></div>
<script>
    let dump;

    ace.config.set('basePath', 'https://unpkg.com/ace-builds@1.33.1/src-min/');
    const editor = ace.edit('config', {
        mode: 'ace/mode/yaml',
    });

    document.getElementById('save').addEventListener('click', async () => {
        let r = await fetch('api/config', {cache: 'no-cache'});
        if (r.ok && dump !== await r.text()) {
            alert('Config was changed from another place. Refresh the page and make changes again');
            return;
        }

        r = await fetch('api/config', {method: 'POST', body: editor.getValue()});
        if (r.ok) {
            alert('OK');
            dump = editor.getValue();
            await fetch('api/restart', {method: 'POST'});
        } else {
            alert(await r.text());
        }
    });

    window.addEventListener('load', async () => {
        const r = await fetch('api/config', {cache: 'no-cache'});
        if (r.status === 410) {
            alert('Config file is not set');
        } else if (r.status === 404) {
            editor.setValue(''); // config file not exist
        } else if (r.ok) {
            dump = await r.text();
            editor.setValue(dump);
        } else {
            alert(`Unknown error: ${r.statusText} (${r.status})`);
        }
    });
</script>
</body>
</html>
